using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.CompositeUI;
using System.Windows.Forms;
using Jbe.CABExtension.WinForms.Workspaces;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeUI.WinForms;
using System.Drawing;

namespace Jbe.CABExtension.WinForms
{
    /// <summary>
    /// Extends FormShellApplication to show a splash screen during application startup.
    /// </summary>
    /// <typeparam name="TWorkItem">The type of the root application work item.</typeparam>
    /// <typeparam name="TShell">The type for the shell to use.</typeparam>
    public class SplashFormShellApplication<TWorkItem, TShell> : FormShellApplication<TWorkItem, TShell>
        where TWorkItem : WorkItem, new()
        where TShell : Form
    {
        private Form splashForm;

        /// <summary>
        /// Starts the application and shows the splash screen during the startup sequence.
        /// </summary>
        /// <remarks>
        /// By default the color magenta is used as transparent color.
        /// </remarks>
        /// <param name="splashImage">The Image to show as splash screen.</param>
        public virtual void SplashRun(Image splashImage)
        {
            SplashRun(splashImage, Color.Magenta);
        }

        /// <summary>
        /// Starts the application and shows the splash scree during the startup sequence.
        /// </summary>
        /// <param name="splashImage">The Image to show as splash screen.</param>
        /// <param name="transparentColor">The color used for transparent areas.</param>
        public virtual void SplashRun(Image splashImage, Color transparentColor)
        {
            splashForm = new SplashForm(splashImage, transparentColor);
            SplashRun(splashForm);
        }

        /// <summary>
        /// Starts the application and shows the splash screen during the startup sequence.
        /// </summary>
        /// <param name="splashForm">The Form to show as splash screen.</param>
        public virtual void SplashRun(Form splashForm)
        {
            this.splashForm = splashForm;
            splashForm.Show();
            splashForm.Update();

            Run();
        }

        protected override void AfterShellCreated()
        {
            base.AfterShellCreated();
            if (splashForm != null)
            {
                Shell.Activated += new EventHandler(ShellActivated);
            }
        }

        private void ShellActivated(object sender, EventArgs e)
        {
            Shell.Activated -= ShellActivated;
            splashForm.Hide();
            splashForm.Dispose();
            splashForm = null;

            Shell.Focus();
        }
    }
}
